package org.flexqueries2.core
{
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import org.flexqueries2.components.messagebox.Message;
	import org.flexqueries2.core.events.SqlEvent;
	import org.flexqueries2.utils.crypto.Base64;

	/**
	 * Evenément lancé quand la transaction a été exécutée avec succès
	 */ 
	[Event(name="transactionComplete", type="org.flexqueries2.core.events.SqlEvent")]
	
	/**
	 * Evenément lancé quand la transaction a rencontré une erreur
	 */ 
	[Event(name="transactionError", type="org.flexqueries2.core.events.SqlEvent")]
	
	public class SqlTransaction extends EventDispatcher
	{
		[Bindable]
		public var isPending:Boolean = false;
		
		private var cmd_arr:ArrayCollection = new ArrayCollection([]);
		
		public function SqlTransaction()
		{
		}
		
		public function resetCommands():void
		{
			cmd_arr = new ArrayCollection([]);
		}
		
		public function addCommand(sql:String, sqlParams:Array = null):void
		{
			if(sqlParams == null)
				sqlParams = [];
			
			var q:SqlQuery = new SqlQuery();
			q.sql = sql;
			q.sqlParams = sqlParams;
			cmd_arr.addItem(q);
		}
		
		public function executeAsync():void
		{
			isPending = true;
			
			var transaction:XML = <transaction/>;
			for each(var q:SqlQuery in cmd_arr)
				transaction.appendChild(q.asXML);
				
			var payload:String = Base64.encode(transaction.toXMLString());
			var http:HTTPService = SqlQuery.getNewHTTPService();
			
			http.addEventListener(ResultEvent.RESULT, onTransactionResult);
			http.addEventListener(FaultEvent.FAULT, onFault);
			
			http.send({action: 'transaction', payload: payload});
		}
		
		private function onTransactionResult(e:ResultEvent):void
		{
			var x:XML = XML(e.result);

			x.errorCode = Base64.decode(x.errorCode.toString());
			if(Number(x.errorCode) != 0)
			{
				dispatchEvent(new SqlEvent(SqlEvent.TRANSACTION_ERROR));
				Message.showStatic(Base64.decode(x.value.toString()));
			}
			else
			{
				dispatchEvent(new SqlEvent(SqlEvent.TRANSACTION_COMPLETE));
			}
									
			isPending = false;
		}
		
		private function onFault(e:FaultEvent):void
		{
			Message.showStatic(e.message.body.toString());
		}
	}
}